package com.wt.springsamples.security.handler;

import com.alibaba.fastjson.JSON;
import com.wt.springsamples.common.ApiResult;
import com.wt.springsamples.common.SpringContextHolder;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ApiLogoutSuccessHandler implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        //获取Bearer Token
        BearerTokenResolver bearerTokenResolver= new  DefaultBearerTokenResolver();
        JwtDecoder jwtDecoder = SpringContextHolder.getBean(JwtDecoder.class);
        String bearerToken;

        try {
            bearerToken  = bearerTokenResolver.resolve(request);
            Jwt jwt = jwtDecoder.decode(bearerToken);
            ApiResult<String> result = ApiResult.ok("操作成功");
            out.write(JSON.toJSONString(result));
        }catch (Exception e){
            out.write(JSON.toJSONString(ApiResult.fail("未登录或参数无效")));
            return;
        }
    }
}
